import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:xunlongchi/bloc/time_bloc.dart';
import 'package:xunlongchi/ui/home/home_page.dart';
import 'package:xunlongchi/util/app_util.dart';
import 'package:xunlongchi/widgets/animated_roate.dart';
import 'package:xunlongchi/widgets/animated_scale.dart';
import 'package:xunlongchi/widgets/fade_route.dart';
import 'package:xunlongchi/widgets/taiji.dart';

class SplashPage extends StatefulWidget {
  const SplashPage({Key key}) : super(key: key);

  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  ///是否旋转
  bool _roate = false;

  ///是否缩放
  double _scale = 0;

  @override
  void initState() {
    super.initState();

    Future.delayed(const Duration(seconds: 0), () async => await _ready());
  }

  ///准备
  _ready() async {
    bool _permission = true;

    setState(() {
      _roate = true;
      _scale = 1;
    });

    ///请求定位权限
    _permission =
        _permission && await XL.checkPermission(Permission.locationWhenInUse);

    if (_permission) {
      BlocProvider.of<TimeBloc>(context).start();
      Future.delayed(const Duration(seconds: 1), () async {
        await Navigator.of(context).pushAndRemoveUntil(
            FadeRoute(builder: (_) => const HomePage()), (_) => false);
      });
    } else {
      SystemNavigator.pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    XL.initScreen(context);

    return WillPopScope(
      onWillPop: () async {
        return Future.value(false);
      },
      child: Scaffold(
        backgroundColor: Colors.black,
        body: Center(
          child: AnimatedRotation(
            turn: _roate ? 2 : 0,
            curve: Curves.easeOutCirc,
            duration: const Duration(seconds: 1),
            child: AnimatedScale(
              scale: _scale,
              duration: const Duration(seconds: 1),
              child: const Taiji(),
            ),
          ),
        ),
      ),
    );
  }
}
